package util;

import org.apache.commons.dbcp.BasicDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;


public class DBUtils {
	
	private static DataSource dataSource;

	private static final String className = "oracle.jdbc.OracleDriver";
	private static final String url = "jdbc:oracle:thin:@//ZHA-ITA077-w7:1521/ita3";
	private static final String username = "groupMC";
	private static final String password = "123";

	private static BasicDataSource bds;
	public static void setDBCPBds(){
		System.out.println("init....DBCPdatasource...");
		bds = new BasicDataSource();
		bds.setDriverClassName(className);
		bds.setUrl(url);
		bds.setUsername(username);
		bds.setPassword(password);
		bds.setMaxActive(10);
		DBUtils.dataSource = bds;
	}

	static{

		Context initContext;
		try {
			initContext = new InitialContext();
			Context envContext = (Context)initContext.lookup("java:/comp/env");
			dataSource = (DataSource)envContext.lookup("jdbc/myoracle");
		} catch (NamingException e) {
			e.printStackTrace();
		}

	}
	
	public static Connection createConnection(){
		Connection conn = null;
		try {
			conn = dataSource.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	public static void close(Connection conn,PreparedStatement pst,ResultSet rs){
		try {
			if (rs!=null) {
				rs.close();
			}
			if (pst!=null) {
				pst.close();
			}
			if (conn!=null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}
}
